<?php

class Room
{
    protected static $_dbh;
    
    protected $_data = array();
    
    protected $_roomId;
    
    public function __construct($room_id)
    {
        self::$_dbh = Framework_Registry::get('dbh');
        $this->_roomId = $room_id;
    }
    
	 /**
	 * получаем список комнат
	 * @return array (rows,totalrows)
	 * @param str $order поле, по которому сортировать
	 * @param bool $desc порядок сортировки
	 * @author kiote
	 */
    public static function getRooms($order='room_id',$desc = 0,$page = 0,$sum = 0, &$paging = null)
    {
    	$desc = ($desc)? 'DESC' : '';
	 	$rows =  Framework_Registry::get('dbh')->
			selectPage($total_rows,
						"SELECT room_id, room_name, room_status, COUNT(online_user_id) AS online
                         FROM `room`
                         LEFT JOIN online ON room_id = online_room_id
                         GROUP BY room_id
						 ORDER BY $order $desc
						 { LIMIT ?d,?d }", $sum*$page, (!$sum) ? DBSIMPLE_SKIP : $sum);
		if (isset($paging)) $paging = paging($page, $sum, $total_rows);
		return $rows;
		
    }

	
    public static function getOpenRooms()
    {
        // Очищаем таблицу online от зомби
        Framework_Registry::get('dbh')->query("DELETE FROM online
                                               WHERE (UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(online_updated)) > 300");
        return Framework_Registry::get('dbh')->select("SELECT room_id, room_name, COUNT(online_user_id) AS online
                                                       FROM `room`
                                                       LEFT JOIN online ON room_id = online_room_id
                                                       WHERE room_status = 'open'
                                                       GROUP BY room_id");
    }
    
    public static function getUserRooms($user_id)
    {
	 return empty($user_id) ? null : Framework_Registry::get('dbh')
	   ->select("SELECT room_id, room_name, room_status, COUNT(online_user_id) AS online
                 FROM `room`
                 LEFT JOIN online ON room_id = online_room_id
                 LEFT JOIN invite ON room_id = invite_room_id
                 WHERE (invite_room_id IS NULL AND room_status = 'open')
                    OR (invite_room_id IS NOT NULL AND invite_user_id_to=?)
                 GROUP BY room_id", $user_id);

    }
    
    public static function clean($user_id)
    {
        return empty($user_id) ? null : Framework_Registry::get('dbh')->query('DELETE FROM online
                                                                             WHERE online_user_id=?', $user_id);
    }
    
    public static function cleanOnline()
    {
        return Framework_Registry::get('dbh')
            ->query('DELETE FROM online
                     WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(online_updated) > 300');
    }
	
	/**
	 * by kiote
	 * удаляем комнату
	 */
	public static function delete($room_id)
	{
		Framework_Registry::get('dbh')->query("DELETE FROM room 
												WHERE room_id=?",$room_id);
	}
	
	/**
	 * by kiote 
	 * добавляем комнату
	 * @return 
	 * @param $roomName Object
	 * @param $roomStatus Object
	 */
	public static function add($room_name, $room_status = 'open')
	{
		return @Framework_Registry::get('dbh')->query("INSERT INTO room 
														SET room_name=?,
														room_status=?",$room_name,$room_status);
	}
	
	public function isUserAccess($user_id)
    {
        $this->_data = self::$_dbh->selectRow("SELECT * FROM ?_room
                                               LEFT JOIN invite ON room_id = invite_room_id
                                               WHERE room_id=?
                                                   AND (room_status='open' OR (invite_room_id IS NOT NULL AND invite_user_id_to=?))",
                                               $this->_roomId, $user_id);
        if (!is_array($this->_data) || !sizeof($this->_data)) {
            return false;
        }
    	return true;
    }
	
    public function __get($value)
    {
        return array_key_exists($value, $this->_data) ? $this->_data[$value] : null;
    }
    
    public function getRoomMessages($sum = 10, $page = 0, &$paging = array(), $smiles = true)
    {
        switch ($smiles) {
        	case false:
        	   $smiles = 'chat_message';
        	break;
        	
        	default:
        		$smiles = 'SMILE(chat_message)';
        	break;
        }
        
        $result = self::$_dbh
            ->selectPage($total_rows,
                         "SELECT *, UNIX_TIMESTAMP(chat_created) AS created, $smiles AS chat_message
                          FROM chat
                          LEFT JOIN user ON chat_user_id = user_id
                          WHERE chat_room_id=? AND chat_user_id NOT IN (SELECT block_user_id_to
                                                                        FROM block
                                                                        WHERE block_user_id_from=?)
                          ORDER BY chat_id DESC LIMIT ?d, ?d",
                          $this->_roomId,
                          $this->_user->getUserId(),
                          $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);

        return $result;
    }
    
    public function addMessage($user_id, $message)
    {
        if(empty($user_id) || empty($message)) return null;
        $message = strip_tags($message);
        
        return self::$_dbh->query("INSERT INTO chat
                                   SET chat_message=?, chat_room_id=?, chat_user_id=?",
                                   $message, $this->_data['room_id'], $user_id);
    }
    
    public function getRoomId()
    {
        return $this->_roomId;
    }
	
	/**
	 * @author kiote
	 * @return 
	 */
    public function getUsersOnline()
    {
	return self::$_dbh->select('SELECT * FROM online
									LEFT JOIN user ON online_user_id = user_id
									WHERE online_room_id = ?
									ORDER BY user_login', $this->_data['room_id']);	

	}

	/**
	 * kiote
	 * @return 
	 * @param $user Object
	 */
    public function addUser(User_Abstract $user)
    {
        if (empty($user)) return null;
        // Пытаемся обновиться, если не получится записываем нового юзера
        $row = self::$_dbh->query("UPDATE online SET online_updated=NOW(),
													online_room_id=?
                                   WHERE online_user_id=?", $this->_data['room_id'],$user->getUserId());
        if (!$row) {
        	$sql = "INSERT INTO online
                                        SET online_user_id=".$user->getUserId().",
                                            online_room_id=".$this->_data['room_id'].",
                                            online_updated=NOW(),
                                            online_created=NOW()";
            $row = @self::$_dbh->query('INSERT INTO online
                                        SET online_user_id=?,
                                            online_room_id=?,
                                            online_updated=NOW(),
                                            online_created=NOW()',
                                        $user->getUserId(), $this->_data['room_id']);
        }
        $this->_user = $user;
        return $row;
    }
}